package com.snow.service;

import com.snow.annotation.RequirePermission;
import com.snow.jpa.ITenant;
import com.snow.model.ILoginUser;
import com.snow.view.WebResponse;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * 权限业务
 *
 * @author by 13119
 */
public interface IAuthComponent {

    /**
     * 获取当前登录系统用户
     * null 未登录
     */
    ILoginUser getCurrentUser();

    /**
     * 获取当前登录租户
     */
    ITenant getCurrentTenant();


    /**
     * 根据域名获取租户
     */
    ITenant findTenant(String subdomain);

    /**
     * 当前用户是否拥有某个权限
     */
    Boolean havePermission(RequirePermission needPermission);

    /**
     * 用户信息校验失败
     */
    @SneakyThrows
    default void onAuthFail(HttpServletResponse response) {
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        ServletOutputStream output = response.getOutputStream();
        byte[] resultBytes = WebResponse.fail(HttpStatus.UNAUTHORIZED.value(), "未登录或登录信息已过期").toString().getBytes(StandardCharsets.UTF_8);
        output.write(resultBytes);
        response.setContentLength(resultBytes.length);
        output.close();
    }

    /**
     * 权限信息校验失败
     */
    @SneakyThrows
    default void onPermissionFail(HttpServletResponse response) {
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        ServletOutputStream output = response.getOutputStream();
        byte[] resultBytes = WebResponse.fail(HttpStatus.FORBIDDEN.value(), "暂无操作权限，请联系管理员").toString().getBytes(StandardCharsets.UTF_8);
        output.write(resultBytes);
        response.setContentLength(resultBytes.length);
        output.close();
    }

}
